package com.ruoyi.yuwen.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.newAdd.returnResult.Data;
import com.ruoyi.common.newAdd.returnResult.Res;
import com.ruoyi.common.newAdd.utils.TimeUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.yuwen.domain.*;
import com.ruoyi.yuwen.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单Controller
 * 
 * @author ruoyi
 * @date 2023-02-27
 */
@RestController
@RequestMapping("/yuwen/order")
public class OrderController extends BaseController
{
    @Autowired
    private IOrderService orderService;

    @Autowired
    private IUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IUserGoodsService userGoodsService;

    @Autowired
    private ICommissionService commissionService;

    @Autowired
    private IBillService billService;

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('yuwen:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(Order order)
    {
        startPage();
        List<Order> list = orderService.selectOrderList(order);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('yuwen:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Order order)
    {
        List<Order> list = orderService.selectOrderList(order);
        ExcelUtil<Order> util = new ExcelUtil<Order>(Order.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('yuwen:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(orderService.selectOrderById(id));
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('yuwen:order:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Order order)
    {
        return toAjax(orderService.insertOrder(order));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('yuwen:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Order order)
    {
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('yuwen:order:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(orderService.deleteOrderByIds(ids));
    }


    /** 前端接口 **************************************************************************************************** */
    /** 前端接口 **************************************************************************************************** */
    /** 前端接口 **************************************************************************************************** */


    /**
     * 订单列表（进货明细查询订单用户，出货明细查询上级用户，完结明细查询订单用户和上级用户）
     * @param type 业务类型（0:完结明细，1：进货明细，2：出货明细）
     * @param stockType 进出库类型（0:全部，1：入库，2：出库）
     * @return
     */
    @GetMapping("/front/orderList")
    public Res orderList(@RequestParam("type")Integer type,
                         @RequestParam("stockType")Integer stockType){

        Long userId = tokenService.getUserId();

        Order order = new Order();

        List<Order> list = new ArrayList<>();
        startPage();
        if (type==0){
            if (stockType==0){
                list = orderService.selectOrderListByUserIdOrFatherId(userId);
            }
            if (stockType==1){
                order.setUserId(userId);
                list = orderService.selectOrderList(order);
            }
            if (stockType==2){
                order.setFatherId(userId);
                list = orderService.selectOrderList(order);
            }
            for (int i = 0;i < list.size();i++){
                Order item = list.get(i);
                if (item.getUserId()==userId){
                    list.get(i).setChangeNum("+"+item.getNum());
                }else {
                    list.get(i).setChangeNum("-"+item.getNum());
                }
            }
        }
        if (type==1){
            order.setUserId(userId);
            list = orderService.selectOrderList(order);
        }
        if (type==2){
            order.setFatherId(userId);
            list = orderService.selectOrderList(order);
        }

        Long total = new PageInfo(list).getTotal();
        Data data = Data.ok().put("total",total).put("list",list);
        return Res.ok().put("data", data);
    }

    /**
     * 订单详情
     * @param orderId
     * @return
     */
    @GetMapping("/front/orderInfo")
    public Res orderInfo(@RequestParam("orderId")Long orderId){
        Order order = orderService.selectOrderById(orderId);
        Data data = Data.ok().put("order",order);
        return Res.ok().put("data", data);
    }

    /**
     * 添加订单
     * @param order
     * @return
     */
    @PostMapping("/front/orderAdd")
    public Res orderAdd(@RequestBody Order order){

        Long userId = tokenService.getUserId();
        User user = userService.selectUserById(userId);
        User father = userService.selectUserById(user.getFatherId());

        if (father.getUserLevel()==101l){
            if (user.getUserLevel()==103l){
                return Res.errorShowMsg("分公司身份未审核，无法下单！");
            }
        }

        order.setState(0);
        order.setOrderOn(createOrderSourceId());
        order.setAddTime(TimeUtil.getStringTime("yyyy-MM-dd HH:mm:ss"));
        order.setUserId(userId);
        order.setUserName(user.getName());
        order.setFatherId(user.getFatherId());
        orderService.insertOrder(order);
        return Res.okShowMsg("订单添加成功！");
    }

    /**
     *订单审核（过审或驳回）
     * @param orderId 订单号
     * @param isOk 是否过审（0：过审，1：驳回）
     * @param reason 驳回理由（当isOk为1时必填）
     * @return
     */
    @GetMapping("/front/orderVerify")
    public Res orderVerify(@RequestParam("orderId")Long orderId,
                           @RequestParam("isOk")Integer isOk,
                           @RequestParam(value = "reason",required = false)String reason){

        Order order = orderService.selectOrderById(orderId);
        if (isOk==0){
            /** 需要增减用户库存 */
            User father = userService.selectUserById(order.getFatherId());
            User user = userService.selectUserById(order.getUserId());

            /** 查询并修改出货方商品库存 */
            UserGoods temp = new UserGoods();
            temp.setGoodsId(order.getGoodsId());
            temp.setUserId(order.getFatherId());
            List<UserGoods> fatherGoodsList = userGoodsService.selectUserGoodsList(temp);
            if (fatherGoodsList.size()<=0){
                return Res.errorShowMsg("您的库存余额不足，请尽快补足库存！");
            }
            UserGoods fatherGoods = fatherGoodsList.get(0);
            if (fatherGoods.getStock()<order.getNum()){
                return Res.errorShowMsg("您的库存余额不足，请尽快补足库存！");
            }
            fatherGoods.setStock(fatherGoods.getStock()-order.getNum());
            userGoodsService.updateUserGoods(fatherGoods);

            /** 查询并修改进货方商品库存 */
            temp.setUserId(order.getUserId());
            List<UserGoods> userGoodsList = userGoodsService.selectUserGoodsList(temp);
            UserGoods userGoods = new UserGoods();
            if (userGoodsList.size()<=0){
                userGoods.setGoodsId(order.getGoodsId());
                userGoods.setGoodsName(order.getGoodsName());
                userGoods.setUserId(order.getUserId());
                userGoods.setUserName(user.getName());
                userGoods.setStock(order.getNum());
                userGoodsService.insertUserGoods(userGoods);
            }else {
                userGoods = userGoodsList.get(0);
                userGoods.setStock(userGoods.getStock()+order.getNum());
                userGoodsService.updateUserGoods(userGoods);
            }
            /** 修改订单状态为已审核 */
            order.setState(2);

            /** 审核成功后判断上级用户是否产生佣金，产生条件为role=102 */
            if (father.getUserLevel()==102l){
                Commission commission = commissionService.selectCommissionById(1l);
                Long amout = father.getBalance()+order.getNum()*commission.getAmount();
                father.setBalance(amout.intValue());
                userService.updateUser(father);
                Bill bill = new Bill();
                bill.setOrderNo(order.getOrderOn());
                bill.setNum(order.getNum());
                bill.setAmout(amout);
                bill.setType(0);
                bill.setUserId(father.getId());
                bill.setUserName(father.getName());
                bill.setPhone(father.getPhone());
                bill.setAddTime(TimeUtil.getStringTime("yyyy-MM-dd HH:mm:ss"));
                bill.setState(0);
                billService.insertBill(bill);
            }

        }else {
            order.setState(1);
            order.setReason(reason);
        }
        orderService.updateOrder(order);
        return Res.okShowMsg(isOk==0?"订单过审成功！":"订单驳回成功！");
    }

    /**
     *订单激活
     * @param orderId 订单id
     * @return
     */
    @GetMapping("/front/orderEnd")
    public Res orderEnd(@RequestParam("orderId")Long orderId){
        Order order = orderService.selectOrderById(orderId);
        if (order.getState()!=2){
            return Res.errorShowMsg("订单未过审，无法激活！");
        }

        order.setState(3);
        orderService.updateOrder(order);

        /** 激活成功后上级用户添加激活成功数量 */
        User father = userService.selectUserById(order.getFatherId());
        father.setActivateNum(father.getActivateNum()+order.getNum());

        /** 激活成功后判断上级用户是否产生佣金，产生条件为role=102 */
        if (father.getUserLevel()==102l){
            Commission commission = commissionService.selectCommissionById(1l);
            Long num = father.getBalance()+order.getNum()*commission.getAmount();
            father.setBalance(num.intValue());
        }
        userService.updateUser(father);

        return Res.okShowMsg("订单激活成功！");
    }

    /**
     * 生成时间戳关联的随机字符串
     * @return
     */
    public String createOrderSourceId(){
        String rd = String.format("%04d",new Random().nextInt(9999));
        return TimeUtil.getTime()+rd;
    }
}
